package com.webserver.controller;

import com.webserver.core.DispatcherServlet;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理与用户相关的操作
 */
public class UserController {
    private static File userDir;
    private static File root;
    private static File staticDir;

    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        userDir = new File("./users");
        if (!(userDir.exists())) {
            userDir.mkdirs();
        }
    }

    public void reg(HttpServletResponse response, HttpServletRequest request) {
        //获取用户注册网页上输入的注册信息，获取form表单提交的内容。

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        if (username == null || password == null || nickname == null || ageStr == null || !ageStr.matches("[0-9]+")) {
            File file = new File(staticDir, "./myweb/reg_input_error.html");
            response.setContentFile(file);
            return;
        }

        int age = Integer.parseInt(ageStr);
        System.out.println(username + "," + password + "," + nickname + "," + age);

        File userFile = new File(userDir, username+".obj");
        if (userFile.exists()) {
            File file = new File(staticDir, "./myweb/have_user.html");
            response.setContentFile(file);
            return;
        }
        try (
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            User user = new User(username, password, nickname, age);
            oos.writeObject(user);

            File file = new File(staticDir, "./myweb/reg_success.html");
            response.setContentFile(file);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void login(HttpServletResponse response, HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        File file;
        if (username == null || password == null ) {
            file = new File(staticDir, "./myweb/login_info_error.html");
            response.setContentFile(file);
            return;
        }
        User user = new User();
        file = new File(userDir,username+".obj");
        if (file.exists()) {
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                user = (User) ois.readObject();
                if (user.getPassword().equals(password)){
                    file = new File(staticDir,"./myweb/login_success.html");
                    response.setContentFile(file);
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
            file = new File(staticDir,"./myweb/login_fail.html");
            response.setContentFile(file);




    }


    public void shouAllUser(HttpServletResponse response, HttpServletRequest request){
        List<User> userList = new ArrayList<>();
        File[] userFiles = userDir.listFiles(f->f.getName().endsWith(".obj"));
        for (File userFile : userFiles){
            try (
                    FileInputStream fos = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fos);
            ){
                userList.add((User)ois.readObject());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        File file = new File("userList.html");

        try(PrintWriter pw = new PrintWriter(file,"UTF-8");
        ){
            pw.println("<!DOCTYPE html>\n" +
                    "<html lang=\"en\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>用户列表</title>\n" +
                    "</head>\n" +
                    "<center>\n" +
                    "    <h1>用户列表</h1>"+
                    "<table border=\"1\">\n" );
            pw.println(
                    "        <tr>\n" +
                    "            <td align=\"center\">用户名</td>\n" +
                    "            <td align=\"center\">密码</td>\n" +
                    "            <td align=\"center\">昵称</td>\n" +
                    "            <td align=\"center\">年龄</td>\n" +
                    "        </tr>" );
            for (User user : userList){
            pw.println("<tr>\n" +
                    "            <td align=\"center\">"+user.getUsername()+"</td>\n" +
                    "            <td align=\"center\">"+user.getPassword()+"</td>\n" +
                    "            <td align=\"center\">"+user.getNickname()+"</td>\n" +
                    "            <td align=\"center\">"+user.getAge()+"</td>\n" +
                    "        </tr>\n");
            }
            pw.println("</table>\n" +
                    "</center>\n" +
                    "\n" +
                    "</body>\n" +
                    "</html>");


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentFile(file);

    }


}

